#include"MyMute.hpp"
#include<unistd.h>

using namespace MutexModule;

static int g_ticket = 10000;
Mutex mtx;

void* BuyTicket(void* args)
{
    const char* name = (const char*)args;
    while(true)
    {
        //局部变量，出作用域自动调用析构(unlock)
        MutexGuard mutexguard(mtx); 
        if(g_ticket > 0)
        {
            usleep(1000);
            printf("%s buy ticket:%d\n",name,g_ticket);
            g_ticket--;
            usleep(50);
        }
        else
        {
            break;
        }
    }
    return nullptr;
}

int main()
{

    pthread_t tid1,tid2,tid3,tid4;
    pthread_create(&tid1,nullptr,BuyTicket,(void*)"pthread-1");
    pthread_create(&tid2,nullptr,BuyTicket,(void*)"pthread-2");
    pthread_create(&tid3,nullptr,BuyTicket,(void*)"pthread-3");
    pthread_create(&tid4,nullptr,BuyTicket,(void*)"pthread-4");

    pthread_join(tid1,nullptr);
    pthread_join(tid2,nullptr);
    pthread_join(tid3,nullptr);
    pthread_join(tid4,nullptr);


    return 0;
}